#!/bin/bash
set +e

usb_port=/dev/ttyUSB0

loop=1
ping_time=100

at=""
ppp=""
diag=""

python2 nvm.py
DATE="$(date +%m%d-%H%M)_cmux"
mkdir ../log/$DATE
sed -i "s|log_dir = .*|log_dir = \"$DATE\"|" ../cfg/at/other.cfg
sed -i "s|test_ppp_loop = .*|test_ppp_loop = $loop|" ../cfg/at/other.cfg
sed -i "s|ppp_ping_loop = .*|ppp_ping_loop = $ping_time|" ../cfg/at/other.cfg

./../bin/cmux "$usb_port"
port_list=(`ls /dev/ttyGSM*`)
echo ${port_list[*]}
if [ ${#port_list[*]} -ge 4 ];then
	at=${port_list[0]}
	ppp=${port_list[1]}
    diag=${port_list[2]}       
else
    exit "open fail"
fi

if [ ! "$at" = "" ];then
	sed -i "s|dev_port = .*|dev_port = \'$at\'|" ../cfg/at/other.cfg
fi

if [ ! "$ppp" = "" ];then
	sed -i "s|DEVICE=/dev/.*|DEVICE=$ppp|" ../cfg/ppp/air-ppp-on
	sed -i "s|DEVICE=/dev/.*|DEVICE=$ppp|" ../cfg/ppp/air-ppp-off
	sed -i "s|DEVICE=/dev/.*|DEVICE=$ppp|" ../cfg/ppp/air-ppp-status
fi

../bin/diag "../log/$DATE/log_$(date +%H:%M:%S)" - - $diag &
DIAG_PID=$!

while true
do
    python2 main.py
    if [ $? = "5" ]; then
        break
    fi
done

kill -s 0 $DIAG_PID &> /dev/null
if [ $? = '0' ]; then
    # pkill --signal SIGINT diag
    kill -s SIGINT $DIAG_PID
fi
../bin/off-mux
echo quit

